package com.example.app.ui.components

import androidx.compose.animation.AnimatedContentTransitionScope
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.example.app.compositionLocal.LocalUserViewModel
import com.example.app.ui.navigation.Destinations
import com.example.app.ui.screens.ArticleDetailScreen
import com.example.app.ui.screens.LoginScreen
import com.example.app.ui.screens.MainFrame
import com.example.app.viewmodel.UserViewModel

/**
 * 导航控制器
 */
@Composable
fun NavHostApp() {
    val navController = rememberNavController()
    CompositionLocalProvider(value = LocalUserViewModel provides UserViewModel(LocalContext.current)) {
        val userViewModel = LocalUserViewModel.current

        NavHost(navController = navController, startDestination = Destinations.HomeFrame.route) {
            //首页
            composable(Destinations.HomeFrame.route, enterTransition = {
                slideIntoContainer(AnimatedContentTransitionScope.SlideDirection.Right)
            }, exitTransition = {
                slideOutOfContainer(AnimatedContentTransitionScope.SlideDirection.Left)
            }) {
                MainFrame(onNavigateToArticle = {
                    navController.navigate(Destinations.ArticleDetail.route)
                }, onNavigateToStudyHistory = {
                    if (userViewModel.logged) {
                        //已登录
                    } else {
                        //未登录
                        navController.navigate(Destinations.Login.route)
                    }
                })
            }
            //文章详情页
            composable(Destinations.ArticleDetail.route, enterTransition = {
                slideIntoContainer(AnimatedContentTransitionScope.SlideDirection.Left)
            }, exitTransition = {
                slideOutOfContainer(AnimatedContentTransitionScope.SlideDirection.Right)
            }) {
                ArticleDetailScreen(onBack = {
                    navController.popBackStack()
                })
            }

            composable(Destinations.Login.route, enterTransition = {
                slideIntoContainer(AnimatedContentTransitionScope.SlideDirection.Left)
            }, exitTransition = {
                slideOutOfContainer(AnimatedContentTransitionScope.SlideDirection.Right)
            }) {
                LoginScreen {
                    navController.popBackStack()
                }
            }
        }
    }
}

@Preview
@Composable
fun NavHostAppPreview() {
    NavHostApp()
}